<template>
  <view class="report-container">
    <u-loading-page :loading="isLoading" loading-text="加载中..."></u-loading-page>

    <template v-if="!isLoading">
      <!-- 1. Report Target Info (Optional but Recommended) -->
      <view class="target-info section-card" v-if="targetInfo">
          <text class="target-label">举报对象:</text>
          <!-- Display different info based on type -->
          <view v-if="reportType === 'product'" class="target-details">
              <image :src="targetInfo.image" mode="aspectFill" class="target-image product"></image>
              <text class="target-text">商品: {{ targetInfo.title }}</text>
          </view>
          <view v-else-if="reportType === 'user'" class="target-details">
               <image :src="targetInfo.avatar" mode="aspectFill" class="target-image user"></image>
               <text class="target-text">用户: {{ targetInfo.nickname }}</text>
          </view>
          <view v-else-if="reportType === 'message'" class="target-details">
               <text class="target-text message-preview">消息: "{{ targetInfo.contentPreview }}"</text>
          </view>
          <view v-else class="target-details">
              <text class="target-text">ID: {{ targetId }}</text>
          </view>
      </view>

      <!-- 2. Report Reason Selection -->
      <view class="reason-selection section-card">
        <text class="section-title">请选择举报原因</text>
        <u-radio-group v-model="selectedReason" placement="column">
          <u-radio
            :customStyle="{ marginBottom: '16rpx' }"
            v-for="(reason, index) in reportReasons"
            :key="index"
            :label="reason.label"
            :name="reason.value"
          >
          </u-radio>
        </u-radio-group>
      </view>

      <!-- 3. Report Description -->
      <view class="description-section section-card">
        <text class="section-title">详细描述 (必填)</text>
        <u-textarea
          v-model="reportDescription"
          placeholder="请详细说明举报理由，有助于平台快速处理"
          border="surround"
          height="120"
          maxlength="300"
          count
        ></u-textarea>
      </view>

      <!-- 4. Evidence Upload (Optional) -->
      <view class="evidence-upload section-card">
        <text class="section-title">上传证据 (可选，最多5张)</text>
        <u-upload
          :fileList="fileList"
          @afterRead="afterRead"
          @delete="deletePic"
          name="reportEvidence"
          multiple
          :maxCount="5"
          :previewImage="true"
        ></u-upload>
      </view>

      <!-- 5. Submit Button -->
      <view class="submit-button">
        <button
          class="submit-btn"
          type="primary"
          @click="submitReport"
          :loading="isSubmitting"
          :disabled="!selectedReason || !reportDescription.trim()"
        >
          提交举报
        </button>
      </view>
    </template>
  </view>
</template>

<script>
export default {
  data() {
    return {
      reportType: null, // e.g., 'product', 'user', 'message'
      targetId: null,
      isLoading: false, // For loading target info (optional)
      targetInfo: null, // { title?, nickname?, image?, avatar?, contentPreview? }
      reportReasons: [ // Configure these based on your platform needs
        { label: '发布违禁信息', value: 'prohibited_info' },
        { label: '虚假宣传/欺诈', value: 'fraud' },
        { label: '骚扰/辱骂他人', value: 'harassment' },
        { label: '侵犯版权/盗图', value: 'infringement' },
        { label: '恶意行为/刷单', value: 'malicious_behavior' },
        { label: '其他问题', value: 'other' },
      ],
      selectedReason: '',
      reportDescription: '',
      fileList: [],
      uploadedEvidenceUrls: [],
      isSubmitting: false,
    };
  },
  onLoad(options) {
    if (options.type && options.id) {
      this.reportType = options.type;
      this.targetId = options.id;
      // Optionally load target info based on type and id
      // this.loadTargetInfo(); 
    } else {
      uni.showToast({ title: '缺少举报参数', icon: 'error' });
      uni.navigateBack();
    }
  },
  methods: {
     // Optional: Load info about the thing being reported
     async loadTargetInfo() {
         // This is just an example, implement based on your API structure
         if (!this.reportType || !this.targetId) return;
         this.isLoading = true;
         let apiUrl = '';
         switch (this.reportType) {
             case 'product': apiUrl = `/secondhand/product/${this.targetId}/brief`; break;
             case 'user': apiUrl = `/user/${this.targetId}/profile/brief`; break;
             // For messages, you might need to pass content preview directly or fetch it
             default: this.isLoading = false; return; // Don't load if type is unknown
         }
         
         try {
             const res = await this.$api.get(apiUrl);
             this.targetInfo = res.data; 
         } catch (error) {
             console.error("加载举报对象信息失败:", error);
             // Don't block reporting if loading fails
             this.targetInfo = null; 
         } finally {
             this.isLoading = false;
         }
     },

    // --- Image Upload --- (Similar to previous implementations)
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this.fileList.length;
      lists.map((item) => {
          this.fileList.push({ ...item, status: 'uploading', message: '上传中' });
      });

      for (let i = 0; i < lists.length; i++) {
          try {
              // Use a generic upload endpoint or one specific for reports
              const result = await this.$api.upload('/upload/report-evidence', {
                  filePath: lists[i].url,
                  name: 'file',
              });
              let item = this.fileList[fileListLen];
              this.fileList.splice(fileListLen, 1, Object.assign(item, {
                  status: 'success',
                  message: '',
                  url: result.data.url
              }));
              this.uploadedEvidenceUrls.push(result.data.url);
              fileListLen++;
          } catch (uploadError) {
              console.error("Upload failed:", uploadError);
              this.fileList.splice(fileListLen, 1);
              uni.showToast({ title: '证据上传失败', icon: 'none' });
          }
      }
    },
    deletePic(event) {
      const deletedUrl = this.fileList[event.index].url;
      this.fileList.splice(event.index, 1);
      this.uploadedEvidenceUrls = this.uploadedEvidenceUrls.filter(url => url !== deletedUrl);
      // Optional: Call backend to delete the uploaded file
    },
    
    // --- Submission ---
    validateForm() {
        if (!this.selectedReason) {
            uni.showToast({ title: '请选择举报原因', icon: 'none' });
            return false;
        }
        if (!this.reportDescription.trim()) {
            uni.showToast({ title: '请填写详细描述', icon: 'none' });
            return false;
        }
        return true;
    },
    async submitReport() {
        if (!this.validateForm() || this.isSubmitting) return;

        this.isSubmitting = true;
        uni.showLoading({ title: '提交中...' });

        try {
            const payload = {
                reportType: this.reportType,
                targetId: this.targetId,
                reason: this.selectedReason,
                description: this.reportDescription,
                evidenceUrls: this.uploadedEvidenceUrls
            };
            
            // API endpoint to submit the report
            await this.$api.post('/report', payload);

            uni.hideLoading();
            uni.showModal({ 
                title: '提交成功', 
                content: '您的举报已提交，平台将尽快处理。', 
                showCancel: false,
                success: () => {
                     uni.navigateBack();
                }
            });

        } catch (error) {
            uni.hideLoading();
            console.error("举报提交失败:", error);
            uni.showToast({ title: error.message || '提交失败', icon: 'error' });
        } finally {
            this.isSubmitting = false;
        }
    }
  }
};
</script>

<style lang="scss" scoped>
.report-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.section-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.target-info {
    .target-label {
        font-size: 26rpx;
        color: #999;
        margin-bottom: 15rpx;
        display: block;
    }
    .target-details {
        display: flex;
        align-items: center;
        gap: 15rpx;
        .target-image {
            width: 80rpx;
            height: 80rpx;
            border-radius: 8rpx;
            flex-shrink: 0;
             &.user {
                 border-radius: 50%;
             }
        }
        .target-text {
            font-size: 28rpx;
            color: #333;
             &.message-preview {
                font-style: italic;
                color: #666;
                @include text-ellipsis(2); 
             }
        }
    }
}

.reason-selection, .description-section, .evidence-upload {
  .section-title {
    display: block;
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 25rpx;
  }
}

.submit-button {
  margin-top: 40rpx;
  padding: 0 10rpx; // Add some padding if needed
  .submit-btn {
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    border-radius: 45rpx;
    background-color: $u-error; // Use theme color for reporting
    color: #ffffff;
     &::after {
         border: none;
     }
     &[disabled] {
      background-color: lighten($u-error, 20%) !important; 
      color: #ffffff !important;
    }
  }
}
</style> 